import re, random, json
from django.http import JsonResponse, HttpResponse
from django.views import View
from django_redis import get_redis_connection
from ihome.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import send_sms_code

import logging
logger = logging.getLogger('django')

class ImageCodeView(View):
    def get(self, request):
        # 接收参数
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % cur, 300, text)
        # 响应结果
        return HttpResponse(image, content_type='image/jpg')


# 短信验证码
class SMSCodeView(View):
    def post(self, request):
        # 接收参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        cur = data.get('id')
        text_code = data.get('text')
        # 给手机号做标记
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({
                'errno': 400,
                'errmsg': '频繁发送短信'
            })

        # 校验参数
        if not all([mobile, cur, text_code]):
            return JsonResponse({
                'errno': 400,
                'errmsg': '缺少参数'
            })
        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({
                'errno': 400,
                'errmsg': '参数mobile错误'
            })
        # 图形验证码的--提取,删除,验证,短信验证码--生成,保存,发送
        text_code_redis = redis_conn.get('img_%s' % cur)
        # 判断过期
        if not text_code_redis:
            return JsonResponse({
                'errno': 400,
                'errmsg': '图形验证码失效'
            })

        # 删除图形验证码
        try:
            redis_conn.delete('img_%s' % cur)
        except Exception as e:
            logger.error(e)

        redis_conn.delete('img_%s' % cur)
        if text_code.lower() != text_code_redis.lower():
            return JsonResponse({
                'errno': 400,
                'errmsg': '图形验证码错误'
            })
        # 生成短信验证码,保存,发送
        random_num = random.randint(0, 999999)
        sms_code = '%06d' % random_num
        pl = redis_conn.pipeline()
        pl.set('sms_code_%s' % mobile, sms_code, 300)
        pl.set('send_flag_%s' % mobile, 1, 60)
        pl.execute()
        # 发送短信,调用异步任务
        send_sms_code.delay(mobile, sms_code)
        print(sms_code)
        # 响应结果
        return JsonResponse({
            'errno': 0,
            'errmsg': '短信验证码发送成功'
        })
